package com.jy.oms.framework.asyn.task.queue.memory;


import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayedTask implements Delayed {
    private String taskIdentifier;
    private long executeTime;

    public DelayedTask(String taskIdentifier, long taskDelayedSeconds) {
        this.taskIdentifier = taskIdentifier;
        this.executeTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(taskDelayedSeconds);
    }

    /**
     * 用于返回剩余时间
     * 返回小于等于0则到期
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(executeTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 任务排序
     */
    @Override
    public int compareTo(Delayed o) {
        long result = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
        return (int) result;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        DelayedTask that = (DelayedTask) o;
        return taskIdentifier.equals(that.taskIdentifier);
    }

    @Override
    public int hashCode() {
        return Objects.hash(taskIdentifier);
    }

    public String getTaskIdentifier() {
        return taskIdentifier;
    }
}